<template>
    <a-drawer :width="600" :open="open" @close="$emit('update:open', false)">
        <template #title>
            {{ title }}
        </template>

        <a-form
            ref="formRef"
            :model="localForm"
            :rules="formRules"
            layout="vertical"
            autocomplete="off"
            class="permission-form px-4"
        >
            <div class="grid grid-cols-2 gap-3">
                <div v-if="showFlag.routeTitle">
                    <a-form-item :required="requiredFlag.routeTitle" label="菜单名称" name="routeTitle">
                        <a-input v-model:value="localForm.routeTitle" placeholder="如 总览" allow-clear />
                    </a-form-item>
                </div>
                <div v-if="showFlag.routeName">
                    <a-form-item :required="requiredFlag.routeName" label="路由名称" name="routeName">
                        <a-input v-model:value="localForm.routeName" placeholder="如 Overview" allow-clear />
                    </a-form-item>
                </div>

                <div v-if="showFlag.permissionName">
                    <a-form-item :required="requiredFlag.permissionName" label="权限标识" name="permissionName">
                        <a-input
                            v-model:value="localForm.permissionName"
                            placeholder="如 general:sysuser:list"
                            allow-clear
                        />
                    </a-form-item>
                </div>
                <div v-if="showFlag.routePath">
                    <a-form-item :required="requiredFlag.routePath" label="路由地址" name="routePath">
                        <a-input v-model:value="localForm.routePath" placeholder="如 /system/user" allow-clear />
                    </a-form-item>
                </div>

                <div v-if="showFlag.componentPath">
                    <a-form-item :required="requiredFlag.componentPath" label="组件路径" name="componentPath">
                        <a-input v-model:value="localForm.componentPath" placeholder="如 system/user" allow-clear />
                    </a-form-item>
                </div>
                <div v-if="showFlag.icon">
                    <a-form-item label="图标" name="icon">
                        <a-input v-model:value="localForm.icon" placeholder="Antd 图标名或自定义" allow-clear />
                    </a-form-item>
                </div>

                <div v-if="showFlag.activeRoute">
                    <a-form-item label="激活路由" name="activeRoute">
                        <a-input v-model:value="localForm.activeRoute" placeholder="如 system/user" allow-clear />
                    </a-form-item>
                </div>
                <div>
                    <a-form-item label="上级目录" name="parentId">
                        <a-tree-select
                            v-model:value="localForm.parentId"
                            :tree-data="treeDataWithRoot"
                            :field-names="{ children: 'children', label: 'routeTitle', value: 'id' }"
                            allow-clear
                            placeholder="请选择上级目录"
                            class="w-full"
                        />
                    </a-form-item>
                </div>

                <div>
                    <a-form-item label="显示排序" name="sortOrder">
                        <a-input-number style="width: 100%" v-model:value="localForm.sortOrder" :min="0" />
                    </a-form-item>
                </div>
                <div>
                    <a-form-item label="权限级别" name="permissionLevel">
                        <a-radio-group v-model:value="localForm.permissionLevel">
                            <a-radio :value="0">目录</a-radio>
                            <a-radio :value="1">菜单</a-radio>
                            <a-radio :value="2">按钮</a-radio>
                        </a-radio-group>
                    </a-form-item>
                </div>

                <a-form-item label="显示状态" name="isHidden">
                    <a-radio-group v-model:value="localForm.isHidden">
                        <a-radio :value="0">显示</a-radio>
                        <a-radio :value="1">隐藏</a-radio>
                    </a-radio-group>
                </a-form-item>

                <div>
                    <a-form-item label="菜单状态" name="status">
                        <a-radio-group v-model:value="localForm.status">
                            <a-radio :value="1">启用</a-radio>
                            <a-radio :value="0">禁用</a-radio>
                        </a-radio-group>
                    </a-form-item>
                </div>

                <div class="col-span-2">
                    <a-form-item label="描述" name="description">
                        <a-textarea v-model:value="localForm.description" :rows="3" placeholder="请输入权限描述" />
                    </a-form-item>
                </div>
            </div>
        </a-form>

        <template #footer>
            <div class="drawer-footer flex justify-end gap-4 p-4">
                <a-button @click="$emit('update:open', false)">取消</a-button>
                <a-button type="primary" @click="submit" :loading="loading"> 保存 </a-button>
            </div>
        </template>
    </a-drawer>
</template>

<script lang="ts" setup>
import { ref, watch, computed } from 'vue'
import type { FormInstance } from 'ant-design-vue'
import type { SysPermissions, PermissionNode } from '@/api/core/prmissions'

interface Props {
    open: boolean
    title: string
    loading?: boolean
    modelValue?: Partial<SysPermissions> | null
    treeData?: PermissionNode[] | null
}

interface Emits {
    (e: 'update:open', value: boolean): void
    (e: 'submit', value: Partial<SysPermissions>): void
}

const props = withDefaults(defineProps<Props>(), {
    loading: false,
    modelValue: null,
    treeData: null,
})
const emit = defineEmits<Emits>()

const formRef = ref<FormInstance>()
const localForm = ref<Partial<SysPermissions>>({
    permissionName: '',
    routeTitle: '',
    routeName: '',
    routePath: '',
    componentPath: '',
    icon: '',
    activeRoute: '',
    parentId: 0,
    sortOrder: 0,
    permissionLevel: 0,
    isHidden: 0,
    status: 1,
    description: '',
})

// 构造一个带“主类目(id=0)”的树数据，便于选择根级作为父级
const treeDataWithRoot = computed<PermissionNode[]>(() => {
    const children = props.treeData || []
    const root: PermissionNode = {
        id: 0,
        permissionName: '',
        routeTitle: '主类目',
        routeName: 'root',
        routePath: '',
        componentPath: '',
        icon: '',
        activeRoute: '',
        parentId: 0,
        sortOrder: 0,
        permissionLevel: 0,
        isHidden: 0,
        status: 1,
        isDeleted: 0,
        description: '',
        createdAt: '',
        updatedAt: '',
        children,
    }
    return [root]
})

// 根据权限级别动态控制必填：
// 0=目录: 需 routeTitle、routeName、routePath、icon、permissionLevel
// 1=菜单: 需 routeTitle、routeName、routePath、componentPath、permissionLevel
// 2=按钮: 需 permissionName、permissionLevel
const requiredFlag = computed(() => {
    const level = localForm.value.permissionLevel ?? 2
    return {
        routeTitle: level === 0 || level === 1 || level === 2,
        routeName: level === 0 || level === 1,
        permissionName: level === 2 || level === 1,
        routePath: level === 1 || level === 0,
        componentPath: level === 1,
        activeRoute: level === 1,
    }
})

const formRules = computed(() => {
    const r: Record<string, { required: boolean; message: string; trigger: 'blur' | 'change' }[]> = {
        permissionLevel: [{ required: true, message: '请选择权限级别', trigger: 'change' }],
        parentId: [{ required: true, message: '请选择目录', trigger: 'change' }],
        sortOrder: [{ required: true, message: '请输入排序', trigger: 'change' }],
        isHidden: [{ required: true, message: '请选择是否显示', trigger: 'change' }],
        status: [{ required: true, message: '请选择是否启用', trigger: 'change' }],
    }
    if (requiredFlag.value.routeTitle) r.routeTitle = [{ required: true, message: '请输入菜单名称', trigger: 'blur' }]
    if (requiredFlag.value.routeName) r.routeName = [{ required: true, message: '请输入路由名称', trigger: 'blur' }]
    if (requiredFlag.value.permissionName)
        r.permissionName = [{ required: true, message: '请输入权限标识', trigger: 'blur' }]
    if (requiredFlag.value.routePath) r.routePath = [{ required: true, message: '请输入路由路径', trigger: 'blur' }]
    if (requiredFlag.value.componentPath)
        r.componentPath = [{ required: true, message: '请输入组件路径', trigger: 'blur' }]
    if (requiredFlag.value.activeRoute)
        r.activeRoute = [{ required: true, message: '请输入激活路由地址', trigger: 'blur' }]
    return r
})

// 动态显示开关：基于权限级别
// 0=目录: 显示 routeTitle/routeName/routePath/icon，隐藏 permissionName、componentPath
// 1=菜单: 显示 routeTitle/routeName/routePath/componentPath，隐藏 permissionName、icon
// 2=按钮: 仅显示 permissionName，其余隐藏（parentId、status 等基础项除外）
const showFlag = computed(() => {
    const level = localForm.value.permissionLevel ?? 2
    return {
        routeTitle: level === 0 || level === 1 || level === 2,
        routeName: level === 0 || level === 1,
        permissionName: level === 2 || level === 0 || level === 1, // 目录也需要权限标识（根据你的注释）
        routePath: level === 0 || level === 1,
        componentPath: level === 1,
        icon: level === 0 || level === 1,
        activeRoute: level === 1, // 仅菜单场景常用，如需其他场景可放开
    }
})

watch(
    () => props.modelValue,
    (val) => {
        if (!val) {
            // reset
            localForm.value = {
                permissionName: '',
                routeTitle: '',
                routeName: '',
                routePath: '',
                componentPath: '',
                icon: '',
                activeRoute: '',
                parentId: 0,
                sortOrder: 0,
                permissionLevel: 2,
                isHidden: 0,
                status: 1,
                description: '',
            }
            formRef.value?.clearValidate?.()
        } else {
            localForm.value = { ...val }
            formRef.value?.clearValidate?.()
        }
    },
    { immediate: true },
)

const submit = async () => {
    try {
        await formRef.value?.validate()
        emit('submit', { ...localForm.value })
    } catch (err) {
        // 验证失败时保持抽屉打开，错误已由表单项展示
        console.error(err)
    }
}
</script>

<style scoped></style>
